package com.young.filesystem.controller;

import com.young.common.interf.IBaseController;
import com.young.common.model.ResultData;
import com.young.filesystem.service.FileUploadService;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("filesystem")
public class FileUploadController implements IBaseController {

    private final FileUploadService fileUploadService;

    @PostMapping("upload")
    public ResultData uploadFile(
        @RequestParam("file") MultipartFile[] file,
        @RequestParam(required = false) String prefix,
        @RequestParam(required = false) Long expireTime,
        @RequestParam(required = false) Boolean flag,
        @RequestParam(required = false) Boolean withMark,
        HttpServletRequest request
    ) {
        if (null == file || file.length == 0) {
            MultipartHttpServletRequest rq = (MultipartHttpServletRequest) request;
            Map<String, MultipartFile> fileMap = rq.getFileMap();
            List<MultipartFile> multiFileList = new ArrayList<>();
            if (!fileMap.isEmpty()) {
                fileMap.forEach((k, v) -> multiFileList.add(v));
                file = multiFileList.toArray(new MultipartFile[0]);
            }
        }
        if (null == file || file.length == 0) {
            return responseError("文件列表为空！");
        }
        flag = null == flag || flag;
        withMark = null != withMark && withMark;
        return success(fileUploadService.uploadFile(prefix, Arrays.asList(file), null == expireTime ? -1 : expireTime, flag, withMark));
    }

}
